pub mod entity;

use sea_orm::{DbErr, EntityTrait};
use sea_orm::{ActiveModelTrait, ActiveValue, ConnectOptions, Database, DatabaseConnection};
use std::time::{Duration};
use rand::Rng;
use tracing::log;
use tracing_subscriber::EnvFilter;
use crate::entity::dict::Model;

#[tokio::main]
async fn main() -> Result<(), DbErr> {
    // 设置全局日志级别为 info
    EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new("info"))
        //单独设置sea_orm
        .add_directive("sea_orm::driver=debug".parse().unwrap())
        //关闭sqlx自带的日志
        .add_directive("sqlx::query=off".parse().unwrap());


    let mut opt = ConnectOptions::new("postgres://rw_boot:123456@localhost:5432/rw_boot");
    opt.max_connections(1)
        .min_connections(1)
        .connect_timeout(Duration::from_secs(8))
        .acquire_timeout(Duration::from_secs(8))
        .idle_timeout(Duration::from_secs(8))
        .max_lifetime(Duration::from_secs(8))
        .sqlx_logging(true)
        .sqlx_logging_level(log::LevelFilter::Info); // Setting default PostgreSQL schema
    let mut connection = Database::connect(opt).await?;

    // 写入数据
    let dict = insert_dict(&mut connection).await?;
    println!("{:?}", dict);

    // 查询数据
    let list = query_dict(&mut connection).await?;
    list.iter().for_each(|dict| {
        println!("{:?}", dict)
    });

    return Ok(());
}

async fn query_dict(connection: &DatabaseConnection) -> Result<Vec<Model>, DbErr> {
    use entity::dict::Entity as DictDao;
    DictDao::find()
        .all(connection).await
}

async fn insert_dict(connection: &DatabaseConnection) -> Result<Model, DbErr> {
    use entity::dict::ActiveModel as DictModel;
    DictModel {
        group_code: ActiveValue::Set("group_code".to_owned()),
        parent_code: ActiveValue::Set("parent_code".to_owned()),
        code: ActiveValue::Set(random_str().to_owned()),
        display_name: ActiveValue::Set(Some("display_name".to_owned())),
        description: ActiveValue::Set(Some("description".to_owned())),
    }.insert(connection).await
}


fn random_str() -> String {
    let mut rng = rand::thread_rng(); // 创建一个随机数生成器
    let random_string: String = (0..10) // 生成一个长度为10的字符串
        .map(|_| {
            let random_digit = rng.gen_range(0..36); // 生成一个0到35之间的随机数
            if random_digit < 26 { // 如果小于26，则生成字母
                std::char::from_u32('a' as u32 + random_digit).unwrap()
            } else { // 否则生成数字
                std::char::from_u32('0' as u32 + random_digit - 26).unwrap()
            }
        })
        .collect();
    println!("{}", random_string);
    random_string
}